<template>
  <div class="cartWrap">
    <div class="controls">
      <input
        autocomplete="off"
        class="itxt"
        :value="currentValue"
        @blur="handleChange"
        @keyup.enter="handleChange"
      />
      <a @click="add" :class="{ plus: true, disabled: currentValue === max }">
        +
      </a>
      <a @click="dec" :class="{ mins: true, disabled: currentValue === min }">
        -
      </a>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
    value: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      currentValue: this.value,
    }
  },
  methods: {
    handleChange(e) {
      this.currentValue = +e.target.value.trim()
    },
    add() {
      // 如果等于最大值,就不可以加了
      if (this.currentValue === this.max) return
      this.currentValue++
    },
    dec() {
      // 如果等于最小值,就不可以减了
      if (this.currentValue === this.min) return
      this.currentValue--
    },
  },
  watch: {
    currentValue(newValue, oldValue) {
      let currentVal = newValue
      const { min, max } = this
      // 非数字,等于上一次的值
      if (Number.isNaN(newValue)) {
        currentVal = oldValue
      }
      // 小于最小值时,等于最小值
      if (newValue < min) {
        currentVal = min
      }
      // 大于最大值时,等于最大值
      if (newValue > max) {
        currentVal = max
      }
      this.currentValue = currentVal
      this.$emit('input', this.currentValue)
    },
  },
}
</script>

<style lang="less" scoped>
.cartWrap {
  .controls {
    width: 48px;
    position: relative;
    float: left;
    margin-right: 15px;

    .itxt {
      width: 38px;
      height: 37px;
      border: 1px solid #ddd;
      color: #555;
      float: left;
      border-right: 0;
      text-align: center;
    }

    .plus,
    .mins {
      width: 15px;
      text-align: center;
      height: 17px;
      line-height: 17px;
      background: #f1f1f1;
      color: #666;
      position: absolute;
      right: -8px;
      border: 1px solid #ccc;
    }

    .mins {
      right: -8px;
      top: 19px;
      border-top: 0;
    }

    .plus {
      right: -8px;
    }
    .disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }
}
</style>
